package com.sxp.servlet;

import com.sxp.bean.User;
import com.sxp.dao.UserDao;
import com.sxp.dao.impl.UserDaoImpl;
import com.sxp.util.EncryptUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.io.IOException;

/**
 * @author 宋晓盼
 * @since 2019/6/5 10:21
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if (username != null && password != null){
            // 对密码进行加密
            String encryptedPassword = EncryptUtils.md5(password);

            UserDao userDao = new UserDaoImpl();
            // 从数据库中获取对应用户的数据
            User user = userDao.getByUsername(username);

            HttpSession session = req.getSession();

            // 判断用户是否存在
            if (user != null) {
                // 判断密码是否正确
                if (user.getPassword().equals(encryptedPassword)) {
                    session.setAttribute("user", user);
                    resp.sendRedirect("/obs/index.jsp");
                } else {
                    session.setAttribute("msg", "登录失败，密码不正确！");
                    resp.sendRedirect("/obs/message.jsp");
                }
            } else {
                session.setAttribute("msg", "登录失败，用户不存在！");
                resp.sendRedirect("/obs/message.jsp");
            }


        }



    }
}
